package com.ngkj.zmfptCommon.common.util;


import org.springframework.util.ObjectUtils;
import java.util.*;

/**
 * @author ChenHN
 * @since 2021/10/26 creation
 **/
public class TreeUtil {

    public static Map<String, List<Map<String, Object>>> getData(List<Map<String, Object>> list, String target) throws RuntimeException {
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        if (ObjectUtils.isEmpty(list)) {
            return map;
        }
        if (ObjectUtils.isEmpty(target)) {
            throw new RuntimeException("目标属性不能为空！");
        }
        Iterator<Map<String, Object>> treeLists = list.iterator();
        while (treeLists.hasNext()) {
            Map<String, Object> next = treeLists.next();

            String o = next.get(target).toString();
            if (map.containsKey(o)) {
                List<Map<String, Object>> mapList = map.get(o);
                mapList.add(next);
                map.put(o, mapList);
            } else {
                List<Map<String, Object>> mapList = new ArrayList<>();
                mapList.add(next);
                map.put(o, mapList);
            }
        }
        return map;
    }

    public static List<Map<String,Object>> getTree(List<Map<String, Object>> list ,String id ,String pid){
        List<Map<String,Object>> list1 = new ArrayList<>();
        if (ObjectUtils.isEmpty(list)){
            return list1;
        }
        Map<String, List<Map<String, Object>>> listMap = getData(list, pid);
        List<Map<String, Object>> list2 = listMap.get("-1");
        list1.addAll(list2);
        list1.forEach(item->{
            String itemId = item.get(id).toString();
            getChildren(item,itemId,listMap,id);
        });

        return list1;
    }


    public static void getChildren(Map<String,Object> map,String itemId,Map<String, List<Map<String, Object>>> listMap,String id){
        List<Map<String, Object>> list = listMap.get(itemId);
        if (ObjectUtils.isEmpty(list)){
            return ;
        }else{
            map.put("children",list);
            list.forEach(item->{
                getChildren(item,item.get(id).toString(),listMap,id);
            });
        }
    }


}
